package logic

import (
	"box-fresh/model/cache"
	"box-fresh/model/mysql"
	"context"
	"encoding/json"
	"fmt"
	"time"

	"box-fresh/boxfreshrpc/boxfreshrpc"
	"box-fresh/boxfreshrpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ShopSelectLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewShopSelectLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ShopSelectLogic {
	return &ShopSelectLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 商品查询
func (l *ShopSelectLogic) ShopSelect(in *boxfreshrpc.ShopSelectRequest) (*boxfreshrpc.ShopSelectResponse, error) {
	// todo: add your logic here and delete this line

	var shop mysql.Shop

	key := fmt.Sprintf("shopSelect_%d", in.ShopId)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, key).Result()
	if cacheData == "" {
		err := shop.ShopSelect(mysql.DB, in.ShopId)
		if err != nil {
			return nil, err
		}
		jsonData, _ := json.Marshal(shop)
		cache.Rdb.Set(cache.Ctx, key, jsonData, time.Minute*30)
	} else {
		json.Unmarshal([]byte(cacheData), &shop)
	}

	return &boxfreshrpc.ShopSelectResponse{
		ShopId: int64(shop.ID),
		Name:   shop.Name,
		Style:  shop.Style,
		Price:  float32(shop.Price),
	}, nil
}
